<template>
  <a-card class="general-card" title="配送模板" :bordered="false">
    <a-row style="margin-bottom: 16px">
      <a-col :span="16">
        <a-space>
          <a-button @click="refresh">刷新</a-button>
          <a-button type="primary" @click="add">添加</a-button>
        </a-space>
      </a-col>
    </a-row>
    <a-tabs v-model:active-key="shipFormData.currentTab" @change="tabsChange">
      <a-tab-pane key="INFO" title="运费模板">
        <div>
          <div v-for="(item, index) in shipInfo" :key="index">
            <div class="ship-content">
              <div class="ship-title">
                <p>{{ item.name
                }}<a-tag v-if="item.pricingMethod === 'FREE'" color="#ffb400" bordered
                    style="margin-left: 10px">包邮</a-tag></p>
                <p>
                  <a-button size="small" type="text" status="warning" @click="edit(item,index)">修改</a-button>
                  <a-button size="small" type="text" status="danger" @click="remove(item)">删除</a-button>
                </p>
              </div>
              <a-table v-if="item.freightTemplateChildList && item.freightTemplateChildList.length" ref="tablePageRef"
                :columns="columnsTable" :data="item.freightTemplateChildList" :pagination="false"></a-table>
            </div>
          </div>
        </div>
      </a-tab-pane>
      <a-tab-pane v-if="shipFormData.csTab" :key="shipFormData.currentTab">
        <template #title>{{ shipFormData.csTitle }}</template>
        <a-form ref="formRef" :model="shipFormData.form" layout="horizontal" auto-label-width>
          <a-form-item label="模板名称" field="name" :rules="[REQUIRED]">
            <a-input v-model="shipFormData.form.name" allow-clear :style="{ width: '360px' }"></a-input>
          </a-form-item>
          <a-form-item label="计价方式" field="pricingMethod" extra="">
            <a-radio-group v-model="shipFormData.form.pricingMethod" type="button">
              <a-radio value="WEIGHT">按重量</a-radio>
              <a-radio value="NUM">按件数</a-radio>
              <a-radio value="FREE">包邮</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item v-if="shipFormData.form.pricingMethod !== 'FREE'" label="详细设置">
            <div style="width: 100%">
              <a-alert type="warning" :show-icon="false" style="margin-bottom: 10px">点击右侧修改按钮编辑数据</a-alert>
              <a-table ref="tablePageRef" :columns="updateColumnsTable" :data="shipFormData.form.freightTemplateChildList"
                :pagination="false">
                <template #firstCompany="{ record }">
                  <a-input-number v-model="record.firstCompany" :max="999" :min="0" :step="0.1"
                    :style="{ width: '100px' }"></a-input-number>
                </template>
                <template #firstPrice="{ record }">
                  <a-input-number v-model="record.firstPrice" :max="999999" :min="0" :step="0.1"
                    :style="{ width: '100px' }">
                    <template #prefix><span>￥</span></template>
                  </a-input-number>
                </template>
                <template #continuedCompany="{ record }">
                  <a-input-number v-model="record.continuedCompany" :max="999" :min="0" :step="0.1"
                    :style="{ width: '100px' }"></a-input-number>
                </template>
                <template #continuedPrice="{ record }">
                  <a-input-number v-model="record.continuedPrice" :max="999999" :min="0" :step="0.1"
                    :style="{ width: '100px' }">
                    <template #prefix><span>￥</span></template>
                  </a-input-number>
                </template>
                <template #options="{ record, rowIndex }">
                  <a-button size="small" type="text" status="warning" style="margin-right: 10px"
                    @click="editRegion(record, rowIndex)">修改</a-button>
                  <a-button size="small" type="text" status="danger"
                    @click="removeTemplateChildren(record, rowIndex)">删除</a-button>
                </template>
              </a-table>
              <div style="height: 30px; line-height: 30px">
                <div v-if="saveError" style="color: #f53f3f">
                  <icon-info-circle />指定城市为空或指定错误&nbsp;&nbsp;&nbsp;<icon-info-circle />首/续件(重)应输入大于0的数
                </div>
              </div>
            </div>
          </a-form-item>
          <a-form-item>
            <a-button v-if="shipFormData.form.pricingMethod !== 'FREE'" :style="{ marginRight: '10px' }"
              @click="addShipTemplateChildren">
              <template #icon><icon-edit /></template>为指定城市设置运费模板
            </a-button>
            <a-button type="primary" @click="handleSubmit">保存</a-button>
          </a-form-item>
        </a-form>
      </a-tab-pane>
    </a-tabs>

    <!--选择地区弹框-->
    <multipleRegion :is-show="shipFormData.isShowRegion" :disabled-ids="disabledIds" :area-ids="shipFormData.areaIds" @visibleChange="visibleChange"
      @selected="handleSelect"></multipleRegion>
  </a-card>
</template>

<script lang="ts" setup>
import {
addShipTemplate,
deleteShipTemplate,
editShipTemplate,
getShipTemplate,
} from '@/api/shops';
import multipleRegion from '@/components/multiple-region/multiple-region.vue';
import useCurrentInstance from '@/hooks/useCurrentInstance';
import { ColumnsDataRule } from '@/types/global';
import { REQUIRED } from '@/utils/validator';
import { Message } from '@arco-design/web-vue';
import { FormInstance } from '@arco-design/web-vue/es/form';
import { onMounted, reactive, ref } from 'vue';

// 获取modal
const modal = useCurrentInstance().globalProperties?.$modal;
interface formInterface {
  currentTab: string;
  csTab: boolean;
  csTitle: string;
  templateId: string | number;
  form: any;
  selectedIndex: number;
  isShowRegion: boolean;
  areaIds: any; 
}
const disabledIds = ref([] as Array<string>);
const shipFormData = reactive<formInterface>({
  currentTab: 'INFO', // 当前模板tab
  csTab: false, // 添加运费模板是否展示
  csTitle: '添加运费模板', // 模态框标题
  templateId: 0, // 当前模板id
  form: {
    // 添加或编辑表单对象初始化数据
    name: '',
    pricingMethod: 'WEIGHT',
    freightTemplateChildList: [],
  },
  selectedIndex: 0, // 选中的地区模板下标
  isShowRegion: false, // 选择地区弹框
  areaIds: [], // 默认地区数据
});
const formRef = ref<FormInstance>();
const saveError = ref(false); // 是否显示错误提示
const shipInfo = ref<any>([]);
const currentData = ref<any>(""); // 当前点击修改的配送模版数据
const columnsTable: any[] = [
  { title: '运送到', dataIndex: 'area' },
  { title: '首件(重)', dataIndex: 'firstCompany', width: 120 },
  { title: '运费', dataIndex: 'firstPrice', width: 120 },
  { title: '续件(重)', dataIndex: 'continuedCompany', width: 120 },
  { title: '运费', dataIndex: 'continuedPrice', width: 120 },
];
const updateColumnsTable: any[] = [
  { title: '运送到', dataIndex: 'area' },
  {
    title: '首件(重)',
    dataIndex: 'firstCompany',
    width: 100,
    slotName: 'firstCompany',
  },
  {
    title: '运费',
    dataIndex: 'firstPrice',
    width: 100,
    slotName: 'firstPrice',

  },
  {
    title: '续件(重)',
    dataIndex: 'continuedCompany',
    width: 100,
    slotName: 'continuedCompany',
 
  },
  {
    title: '运费',
    dataIndex: 'continuedPrice',
    width: 100,
    slotName: 'continuedPrice',
    
  },
  { title: '操作', width: 180,slotName: 'options' },
];

// 获取运费模板数据
const getData = () => {
  getShipTemplate().then((res) => {
    if (res.data.success) {
      shipInfo.value = res.data.result;
    }
  });
};
// tab切换
const tabsChange = (val: any) => {
  if (val === 'INFO') {
    shipFormData.csTab = false;
  }
};
// 刷新
const refresh = () => {
  shipFormData.csTab = false;
  shipFormData.currentTab = 'INFO';
  getData();
};
// 添加
const add = () => {
  shipFormData.csTab = true;
  shipFormData.csTitle = '添加运费模板';
  shipFormData.currentTab = 'ADD';
  saveError.value = false;
  currentData.value.freightTemplateChildList = [];
  shipFormData.form = {
    pricingMethod: 'WEIGHT',
    name: '',
    freightTemplateChildList: [
      {
        area: '',
        areaId: '',
        firstCompany: 0,
        firstPrice: 0,
        continuedCompany: 0,
        continuedPrice: 0,
        selectedAll: false,
      },
    ],
  };
};
// 修改
const edit = (item:any,index:number) => {
  shipFormData.csTab = true;
  shipFormData.csTitle = '修改运费模板';
  shipFormData.currentTab = 'EDIT';
  shipFormData.form = item;
  shipFormData.templateId = item.id;

  currentData.value = item
  console.log(item)
  saveError.value = false;
};
// 删除
const remove = (item: any) => {
  modal.confirm({
    title: '确认删除',
    content: `您确认要删除此运费模板?`,
    alignCenter: false,
    onOk: async () => {
      deleteShipTemplate(item.id).then((res) => {
        if (res.data.success) {
          Message.success('删除成功！');
          getData();
        }
      });
    },
  });
};

// 添加/编辑运费模板
// 选择地区弹框
const visibleChange = (value: any) => {
  shipFormData.isShowRegion = value;
};
// 选择地区回调
const handleSelect = (value: any) => {
  let area = '';
  let areaId = '';
  if (value != '') {
    value.forEach((child: any) => {
      if (child.selectedList !== '') {
        // 只显示省份
        if (child.selectedAll) {
          area += `${child.name},`;
          areaId += `${child.id},`;
          shipFormData.form.freightTemplateChildList[
            shipFormData.selectedIndex
          ].selectedAll = true;
        }
        child.selectedList.forEach((son: any) => {
          if (child.selectedAll) {
            areaId += `${son.id},`;
          } else {
            // 显示城市
            area += `${son.name},`;
            areaId += `${son.id},`;
          }
        });
      }
    });
  }
  shipFormData.form.freightTemplateChildList[
    shipFormData.selectedIndex
  ].area = area;
  shipFormData.form.freightTemplateChildList[
    shipFormData.selectedIndex
  ].areaId = areaId;
};
// 修改
const editRegion = (item:any, index:number) => {
  shipFormData.selectedIndex = index;
  shipFormData.isShowRegion = true;
  shipFormData.areaIds = item.areaId;
  console.log(item)

  const ids:Array<string> = []
  // 遍历出已经选择的地区ids
 currentData.value.freightTemplateChildList.filter((child:any) => {
    return item.id !== child.id
  }).forEach((area:any) => {
     ids.push(area.areaId.split(','))
  })
  disabledIds.value = ids.flat()
};
// 删除
const removeTemplateChildren = (item:any, index:number) => {
  if (Object.keys(shipFormData.form.freightTemplateChildList).length == 1) {
    Message.success('必须保留一个子模板');
    return;
  }
  shipFormData.form.freightTemplateChildList.splice(index, 1);
};
// 为指定城市设置运费模板
const addShipTemplateChildren = () => {
  const params = {
    area: '',
    areaId: '',
    firstCompany: 0,
    firstPrice: 0,
    continuedCompany: 0,
    continuedPrice: 0,
    selectedAll: false,
  };
  shipFormData.form.freightTemplateChildList.push(params);
};
// 添加或修改模板
const result = ref(true);
const handleSubmit = async () => {
  const auth = await formRef.value?.validate();
  if (!auth) {
    result.value = true;
    if (shipFormData.form.pricingMethod !== 'FREE') {
      // 校验运费模板详细信息
      shipFormData.form.freightTemplateChildList.forEach((item: any) => {
        console.log('判断乾', item)
        item.firstPrice = item.firstPrce || 0
        item.continuedPrice = item.continuedPrice || 0
        if (
          item.area == '' ||
          item.firstCompany == '' ||
          item.continuedCompany == ''
        ) {
          console.log(item)

          saveError.value = true;
          result.value = false;
        }
      });
    } else {
      shipFormData.form.freightTemplateChildList = [];
    }
    if (result.value) {
      if (shipFormData.currentTab === 'ADD') {
        addShipTemplate(shipFormData.form).then((res) => {
          if (res.data.success) {
            Message.success('新增成功！');
            refresh();
          }
        });
      } else if (shipFormData.currentTab === 'EDIT') {
        editShipTemplate(shipFormData.templateId, shipFormData.form).then(
          (res) => {
            if (res.data.success) {
              Message.success('编辑成功！');
              refresh();
            }
          }
        );
      }
    }
  }
};

onMounted(() => {
  getData();
});
</script>

<style scoped lang="less">
.ship-content {
  margin-bottom: 20px;

  .ship-title {
    height: 40px;
    line-height: 40px;
    background-color: #f2f3f5;
    box-sizing: border-box;
    padding: 0 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    >p:nth-of-type(2) {
      .arco-btn {
        margin-left: 10px;
      }
    }
  }

  :deep(.arco-table-th) {
    background-color: transparent;
  }
}
</style>
